﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections.Generic;
using Database.Classes;

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction(DataAccess=DataAccessKind.Read)]
    public static SqlBoolean IsSystemInViewRange(int sId, int PlayerID)
    {
        int biology = GetPlayerInt(PlayerID, "Biology").Value;
        int OrginId = GetPlayerInt(PlayerID, "OrginID").Value;
        if (Distance(sId, OrginId) <= (int)(Math.Floor(biology / 2.0f)))
            return true;
        else
            return false;

    }
    [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
    public static SqlInt32 Distance(int sId1, int sId2)
    {
        List<int> t1= SystemCoordinates(sId1);
        List<int> t2 = SystemCoordinates(sId2);
        return (int)Math.Sqrt(Math.Pow(t1[0] - t2[0], 2) + Math.Pow(t1[0] - t2[0], 2));

    }
    public static List<int> SystemCoordinates(int sid)
    {
        using (SqlConnection conn = new SqlConnection(StaticMethods.ConnectionString()))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Systems Where SystemID = @id", conn))
            {
                cmd.Parameters.Add("@id", SqlDbType.Int).Value = sid;
                SqlDataReader rdr = cmd.ExecuteReader();
                rdr.Read();
                return new List<int>() { rdr.GetInt32(2), rdr.GetInt32(3) };
            }
        }
    }
};

